<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">

      <!-- 自定义操作列 -->
      <template #menu="{ row, index, size }">
        <el-button type="danger" :size="'mini'" icon="el-icon-delete" @click="rowDel(row, index)"
          style="width: 23px; height: 22px; padding: 0; margin-right: 5px;"></el-button>
        <el-button type="text" style="color: #67C23A; margin-left: 5px;" @click="rowDetail(row, index)">详情</el-button>
        <el-button v-if="row.status === 'DISABLED'" type="text" style="color: #67C23A; margin-left: 5px;"
          @click="handleStatusChange(row, 'ENABLED', '启用')">启用</el-button>
        <el-button v-if="row.status === 'ENABLED'" type="text" style="color: #F56C6C; margin-left: 5px;"
          @click="handleStatusChange(row, 'DISABLED', '禁用')">禁用</el-button>
        <el-button type="text" style="color: #E6A23C; margin-left: 5px;"
          @click="handleResetPassword(row)">重置密码</el-button>
      </template>

      <!-- 状态列自定义显示 -->
      <template slot-scope="{ row }" slot="status">
        <el-tag v-if="row.status === 'ENABLED'" type="success">启用</el-tag>
        <el-tag v-else-if="row.status === 'DISABLED'" type="danger">禁用</el-tag>
        <el-tag v-else type="info">{{ row.status }}</el-tag>
      </template>

      <!-- 头像列自定义显示 -->
      <template slot-scope="{ row }" slot="head">
        <el-avatar v-if="row.head" :src="row.head" :size="40"></el-avatar>
        <el-avatar v-else :size="40" icon="el-icon-user"></el-avatar>
      </template>

    </avue-crud>

    <!-- 详情弹窗 -->
    <el-dialog title="代理商详情" :visible.sync="detailDialogVisible" width="80%" :before-close="handleDetailDialogClose"
      center :z-index="9999" :modal-append-to-body="true" :append-to-body="true" custom-class="agent-detail-dialog">
      <div v-loading="detailLoading">
        <!-- 代理商基本信息 -->
        <el-card class="detail-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>基本信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <label>代理商姓名：</label>
                <span>{{ currentAgent.realname }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>手机号：</label>
                <span>{{ currentAgent.mobile }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>状态：</label>
                <el-tag v-if="currentAgent.status === 'ENABLED'" type="success">启用</el-tag>
                <el-tag v-else-if="currentAgent.status === 'DISABLED'" type="danger">禁用</el-tag>
                <el-tag v-else type="info">{{ currentAgent.status }}</el-tag>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 15px;">
            <el-col :span="8">
              <div class="info-item">
                <label>创建时间：</label>
                <span>{{ currentAgent.created_at }}</span>
              </div>
            </el-col>

          </el-row>
        </el-card>

        <!-- 代理商日志表格 -->
        <el-card class="detail-card" shadow="hover" style="margin-top: 20px;">
          <div slot="header" class="card-header">
            <span>线路列表</span>
          </div>
          <el-table :data="detailTableData" :loading="detailTableLoading" style="width: 100%" border stripe>
            <el-table-column prop="created_at" label="创建时间" min-width="180" align="center">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column prop="realname" label="代理商姓名" min-width="150" align="center"></el-table-column>
            <el-table-column prop="mobile" label="手机号" min-width="150" align="center"></el-table-column>
            <el-table-column prop="start_title" label="起始城市" min-width="120" align="center"></el-table-column>
            <el-table-column prop="end_title" label="结束城市" min-width="120" align="center"></el-table-column>
            <el-table-column prop="end_time" label="结束时间" min-width="180" align="center">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.end_time) }}
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container" v-if="detailPage.total > 0" style="margin-top: 20px;">
            <el-pagination @size-change="handleDetailSizeChange" @current-change="handleDetailCurrentChange"
              :current-page="detailPage.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="detailPage.pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="detailPage.total" background>
            </el-pagination>
          </div>
        </el-card>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDetailDialogClose">关闭</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getAgentList, addAgent, deleteAgent, getAgentDetail, setAgentStatus, resetAgentPassword } from "./api/agentManagement";
import { mapGetters } from "vuex";

export default {
  name: "AgentManagementList",
  data () {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectionList: [],
      option: {
        menuType: 'button',
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,
        index: true,
        indexLabel: '序号',
        searchBtnText: '搜索',
        searchBtnIcon: 'el-icon-search',
        emptyBtnText: '重置',
        emptyBtnIcon: 'el-icon-refresh',
        viewBtn: false,
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        addBtn: true,
        addBtnText: '添加代理商',
        addBtnIcon: 'el-icon-plus',
        delBtn: false,
        labelWidth: 120,
        column: [
          {
            label: "关键词",
            prop: "keyword",
            search: true,
            hide: true,
            display: false,
            searchPlaceholder: "请输入姓名/电话",
          },
          {
            label: "代理商姓名",
            prop: "realname",
            search: false,
            rules: [
              {
                required: true,
                message: "请输入代理商姓名",
                trigger: "blur",
              },
            ],
          },

          {
            label: "密码",
            prop: "password",
            type: "password",
            hide: true,
            form: true,
            rules: [
              {
                required: true,
                message: "请输入密码",
                trigger: "blur",
              }
            ],
          },
          {
            label: "手机号",
            prop: "mobile",
            search: false,
            rules: [
              {
                required: true,
                message: "请输入手机号",
                trigger: "blur",
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: "请输入正确的手机号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "状态",
            prop: "status",
            form: true,
            type: "select",
            searchPlaceholder: "请选择状态",
            dicData: [
              { label: "启用", value: "ENABLED" },
              { label: "禁用", value: "DISABLED" }
            ],
            rules: [
              {
                required: true,
                message: "请选择状态",
                trigger: "change",
              },
            ],
          },
          {
            label: "创建时间",
            prop: "created_at",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            display: false,
          },
        ],
      },
      data: [],
      detailDialogVisible: false,
      detailLoading: false,
      detailTableLoading: false,
      currentAgent: {},
      detailTableData: [],
      detailSelectionList: [],
      detailQuery: {},
      detailPage: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },

  computed: {
    ...mapGetters(["permission"]),
    permissionList () {
      return {
        addBtn: this.permission.agent_add,
        viewBtn: this.permission.agent_view,
        delBtn: this.permission.agent_delete,
        editBtn: this.permission.agent_edit,
      };
    }
  },

  mounted () {
    this.onLoad(this.page);
  },

  methods: {
    // 搜索重置
    searchReset () {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索变化
    searchChange (params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 选择变化
    selectionChange (list) {
      this.selectionList = list;
    },

    // 清除选择
    selectionClear () {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 当前页变化
    currentChange (currentPage) {
      this.page.currentPage = currentPage;
    },

    // 每页大小变化
    sizeChange (pageSize) {
      this.page.pageSize = pageSize;
    },

    // 刷新
    refreshChange () {
      this.onLoad(this.page, this.query);
    },

    // 获取数据列表
    onLoad (page, search = {}) {
      this.loading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
      };

      // 处理搜索参数
      if (search.keyword && search.keyword.trim()) {
        param.keyword = search.keyword.trim();
      }
      getAgentList(param).then((res) => {
        if (res.err === 0) {
          const resData = res.data;
          this.page.total = resData.total || 0;
          this.data = resData.list || [];
        } else {
          this.$message.error(res.msg || '获取数据失败');
        }
        this.loading = false;
        this.selectionClear();
      }).catch((error) => {
        console.error('获取代理商列表失败:', error);
        this.$message.error('获取代理商列表失败');
        this.loading = false;
      });
    },

    // 获取代理商详情
    rowDetail (row) {
      this.currentAgent = row;
      this.detailDialogVisible = true;
      this.detailPage.currentPage = 1; // 重置分页
      this.detailTableData = []; // 清空表格数据
      this.onLoadDetail(this.detailPage);
    },

    // 获取详情数据
    onLoadDetail (page, search = {}) {
      this.detailTableLoading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
        id: this.currentAgent.id,
        keyword: '',
      };

      // 处理搜索参数
      if (search.keyword && search.keyword.trim()) {
        param.keyword = search.keyword.trim();
      }

      getAgentDetail(param).then((res) => {
        if (res.err === 0) {
          const resData = res.data;
          this.detailPage.total = resData.total || 0;
          this.detailTableData = resData.list || [];
        } else {
          this.$message.error(res.msg || '获取详情数据失败');
        }
        this.detailTableLoading = false;
      }).catch((error) => {
        console.error('获取代理商详情失败:', error);
        this.$message.error('获取代理商详情失败');
        this.detailTableLoading = false;
      });
    },

    // 编辑
    rowEdit (row, index) {
      this.$refs.crud.rowEdit(row, index);
    },

    // 删除
    rowDel (row, index) {
      this.$confirm('确定删除该代理商吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAgent(row.id).then((res) => {
          if (res.err === 0) {
            this.$message.success('删除成功');
            this.onLoad(this.page, this.query);
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        }).catch(() => {
          this.$message.error('删除失败');
        });
      });
    },

    // 重置密码
    handleResetPassword (row) {
      this.$confirm(`确定要重置代理商"${row.realname}"的密码吗？`, '重置密码确认', {
        confirmButtonText: '确定重置',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetAgentPassword({ id: row.id, mobile: row.mobile }).then((res) => {
          if (res.err === 0) {
            this.$message.success('密码重置成功');
            // 可以显示新密码，如果API返回的话
            this.$alert(`新密码：123456`, '重置成功', {
              confirmButtonText: '确定',
              type: 'success'
            });
            // if (res.data && res.data.newPassword) {

            // }
          } else {
            this.$message.error(res.msg || '密码重置失败');
          }
        }).catch((error) => {
          console.error('重置密码失败:', error);
          this.$message.error('密码重置失败');
        });
      }).catch(() => {
        this.$message.info('已取消重置密码操作');
      });
    },

    // 保存
    rowSave (row, index, done, loading) {
      const data = JSON.parse(JSON.stringify(row));

      // 统一处理新增和编辑的数据结构
      const agentData = {
        username: data.username,
        status: data.status || 'ENABLED', // 使用表单选择的状态，默认启用
        mobile: data.mobile,
        password: data.password,
        realname: data.realname,
        role: [2] // 代理商固定传值 2
      };

      // 如果是编辑模式，添加ID
      if (data.id) {
        agentData.id = data.id;
      }

      addAgent(agentData).then((res) => {
        if (res.err === 0) {
          this.$message.success(data.id ? '更新成功' : '添加成功');
          this.onLoad(this.page, this.query);
          done();
          // 关闭弹窗
          this.$refs.crud.closeDialog();
        } else {
          this.$message.error(res.msg || (data.id ? '更新失败' : '添加失败'));
          loading();
        }
      }).catch(() => {
        this.$message.error(data.id ? '更新失败' : '添加失败');
        loading();
      });
    },

    // 更新
    rowUpdate (row, index, done, loading) {
      const data = JSON.parse(JSON.stringify(row));

      // 统一处理更新数据结构
      const agentData = {
        id: data.id,
        username: data.username,
        status: data.status || 'ENABLED',
        mobile: data.mobile,
        password: data.password,
        realname: data.realname,
        role: [2]
      };

      addAgent(agentData).then((res) => {
        if (res.err === 0) {
          this.$message.success('更新成功');
          this.onLoad(this.page, this.query);
          done();
          // 关闭弹窗
          this.$refs.crud.closeDialog();
        } else {
          this.$message.error(res.msg || '更新失败');
          loading();
        }
      }).catch(() => {
        this.$message.error('更新失败');
        loading();
      });
    },

    // 状态变更处理
    handleStatusChange (data, status, text) {
      this.$confirm(`确定将选择代理商${text}?`, `${text}代理商`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return setAgentStatus({
            id: data.id,
            status: status
          });
        })
        .then(() => {
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        })
        .catch(() => {
          this.$message.error("操作失败");
        });
    },

    // 打开前回调
    beforeOpen (done, type) {
      if (type === 'add') {
        // 新增时设置默认值
        this.form = {
          status: 'ENABLED',
          role: [2]
        };
      }
      done();
    },

    // 详情弹窗关闭
    handleDetailDialogClose () {
      this.detailDialogVisible = false;
      this.currentAgent = {};
      this.detailTableData = [];
      this.detailPage.currentPage = 1;
    },

    // 详情表格搜索重置
    handleDetailSearchReset () {
      this.detailPage.currentPage = 1;
      this.onLoadDetail(this.detailPage);
    },

    // 详情表格搜索变化
    handleDetailSearchChange (params, done) {
      this.detailPage.currentPage = 1;
      this.onLoadDetail(this.detailPage, params);
      done();
    },

    // 详情表格选择变化
    handleDetailSelectionChange (list) {
      this.detailSelectionList = list;
    },

    // 详情表格清除选择
    handleDetailSelectionClear () {
      this.detailSelectionList = [];
      this.$refs.detailCrud.toggleSelection();
    },

    // 详情表格当前页变化
    handleDetailCurrentChange (currentPage) {
      this.detailPage.currentPage = currentPage;
      this.onLoadDetail(this.detailPage);
    },

    // 详情表格每页大小变化
    handleDetailSizeChange (pageSize) {
      this.detailPage.pageSize = pageSize;
      this.onLoadDetail(this.detailPage);
    },

    // 详情表格刷新
    handleDetailRefreshChange () {
      this.onLoadDetail(this.detailPage, this.detailQuery);
    },

    // 详情表格获取数据
    handleDetailOnLoad (page, search = {}) {
      this.detailLoading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
        id: this.currentAgent.id,
        keyword: '',
      };

      // 处理搜索参数
      if (search.keyword && search.keyword.trim()) {
        param.keyword = search.keyword.trim();
      }

      getAgentDetail(param).then((res) => {
        if (res.err === 0) {
          const resData = res.data;
          this.detailPage.total = resData.total || 0;
          this.detailTableData = resData.list || [];
        } else {
          this.$message.error(res.msg || '获取详情数据失败');
        }
        this.detailLoading = false;
      }).catch((error) => {
        console.error('获取代理商详情失败:', error);
        this.$message.error('获取代理商详情失败');
        this.detailLoading = false;
      });
    },

    // 格式化日期时间
    formatDateTime (timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 500;
    }
  }
}

::v-deep .el-avatar {
  border: 1px solid #ebeef5;
}

// 确保弹窗在最上层
.agent-detail-dialog {
  z-index: 9999 !important;

  .el-dialog__wrapper {
    z-index: 9999 !important;
  }

  .el-dialog {
    z-index: 10000 !important;
  }

  .el-dialog__mask {
    z-index: 9998 !important;
  }
}

// 确保弹窗在最顶层
.el-dialog__wrapper.agent-detail-dialog {
  z-index: 9999 !important;
}

.el-dialog.agent-detail-dialog {
  z-index: 10000 !important;
}
</style>
